package com.okwanshiwu.dao.redis;

import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by joryun on 2017/5/8.
 */
public class RedisDao {

    private final Logger logger = Logger.getLogger(RedisDao.class);

    private volatile static JedisPool jedisPool;

    private volatile static RedisDao redisDao = null;

	/**
	 * 获取单例的RedisDao实例
	 * @return
	 */
    public static RedisDao getSingleton(){
    	if(redisDao == null){
			synchronized (RedisDao.class){
				if (redisDao ==null){
		            redisDao = new RedisDao("192.168.0.135",6379);
				}
			}
	    }
		return redisDao;
    }

    private RedisDao(String ip, int port) {
    	JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
	    // 设置初始化连接数
	    jedisPoolConfig.setMaxIdle(30);
	    //设置总连接数
	    jedisPoolConfig.setMaxTotal(100);
	    //设置最大等待的时间
		jedisPoolConfig.setMaxWaitMillis(3000L);
        this.jedisPool = new JedisPool(jedisPoolConfig,ip, port,3000,"123");
    }
	/**
	 * 获取Jedis
	 * @return
	 */
	public Jedis getJedis(){
    	return jedisPool.getResource();
    }
	/**
	 * 获取字符串
	 * @param key 键
	 * @return 如果获取不到jedis，则返回空串
	 */
	public String get(String key){
		Jedis jedis = jedisPool.getResource();
		if(jedis != null && (!"".equals(key)) && key != null){
			return jedis.get(key);
		}
		return "";
	}
	/**
	 * 设置字符串
	 * @param key 键
	 * @param value  值
	 * @return
	 */
	public boolean set(String key,String value){
		Jedis jedis = jedisPool.getResource();
		if(jedis != null){
			String result = jedis.set(key,value);
			jedis.expire(key,60);
			return result.equals("OK")?true:false;
		}
		return false;
	}
	/**
	 * 设置字符串
	 * @param key 键
	 * @param value  值
	 * @param seconds 失效秒数
	 * @return
	 */
	public boolean set(String key,String value,int seconds){
		Jedis jedis = jedisPool.getResource();
		if(jedis != null){
			String result = jedis.set(key,value);
			jedis.expire(key,seconds);
			return result.equals("OK")?true:false;
		}
		return false;
	}


}
